<template>
    <el-table :data="tableData" style="width: 100%">
        <el-table-column fixed prop="itemNumber" label="物料编号" width="150" />
        <el-table-column prop="itemName" label="物料名称" width="120" />
        <el-table-column prop="itemspecification" label="物料规格" width="120" />
        <el-table-column prop="itemType" label="物料类型" width="120" />
        <el-table-column prop="lotNumber" label="批次号" width="120" />
        <el-table-column prop="manufactureDate" label="生产日期" width="120">
            <template #default="scope">
                {{ scope.row.manufactureDate.split('T')[0] }}
            </template>
        </el-table-column>
        <el-table-column prop="expirationDate" label="有效期" width="120">
            <template #default="scope">
                {{ scope.row.expirationDate.split('T')[0] }}
            </template>
        </el-table-column>
        <el-table-column prop="plannedQuantity" label="计划备料数量" width="120" />
        <el-table-column prop="actualQuantity" label="实际备料数量" width="120" />
        <el-table-column prop="unit" label="单位" width="120" />
        <el-table-column prop="productionOrderNumber" label="生产订单号" width="120" />
        <el-table-column fixed="right" label="Operations" min-width="120">
            <template #default="scope">
                <el-button link type="primary" size="small" @click="handleClick(scope.row)">
                    修改
                </el-button>
                <el-button link type="primary" size="small" @click="handleDelete(scope.row)">
                    删除
                </el-button>
            </template>
        </el-table-column>
    </el-table>

    <el-dialog v-model="dialogFormVisible" title="Shipping address" width="500">
        <el-form :model="form">
            <el-form-item label="物料名称" prop="itemName">
                <el-select v-model="form.itemName" placeholder="请选择物料" clearable style="width: 100%">
                    <el-option label="瓶子" value="瓶子" />
                    <el-option label="铁罐" value="铁罐" />
                    <el-option label="纸箱" value="纸箱" />
                </el-select>
            </el-form-item>

            <el-form-item label="物料规格" prop="itemspecification">
                <el-input v-model="form.itemspecification" placeholder="自动填充" />
            </el-form-item>

            <el-form-item label="物料类型" prop="itemType">
                <el-input v-model="form.itemType" placeholder="自动填充" />
            </el-form-item>

            <el-form-item label="批次号" prop="lotNumber">
                <el-input v-model="form.lotNumber" placeholder="自动填充" />
            </el-form-item>

            <!-- 日期信息 -->
            <el-form-item label="生产日期" prop="manufactureDate">
                <el-date-picker v-model="form.manufactureDate" type="date" placeholder="选择生产日期"
                    value-format="YYYY-MM-DD" style="width: 100%" />
            </el-form-item>

            <el-form-item label="有效日期" prop="expirationDate">
                <el-date-picker v-model="form.expirationDate" type="date" placeholder="自动计算" value-format="YYYY-MM-DD"
                    style="width: 100%" />
            </el-form-item>

            <!-- 数量信息 -->
            <el-form-item label="计划备料数量" prop="plannedQuantity">
                <el-input-number v-model="form.plannedQuantity" :min="1" :step="1" style="width: 100%" />
            </el-form-item>

            <el-form-item label="实际备料数量" prop="actualQuantity">
                <el-input-number v-model="form.actualQuantity" :min="0" :step="1" style="width: 100%" />
            </el-form-item>

            <el-form-item label="单位" prop="unit">
                <el-input v-model="form.unit" placeholder="如：个、kg" />
            </el-form-item>

            <el-form-item label="产品名称" prop="productionOrderNumber">
                <el-select v-model="selectedPackaging" placeholder="please select your zone"
                    @change="handlePackagingChange">
                    <el-option v-for="packaging in getpackaginglist" :key="packaging.packagingPlanId"
                        :label="packaging.productRange" :value="packaging.productRange" />
                </el-select>
            </el-form-item>

            <!-- 操作按钮 -->
            <el-form-item>
                <el-button type="primary" @click="submitForm">提交</el-button>
                <el-button @click="resetForm">重置</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>

</template>

<script lang="ts" setup>
import axios from 'axios'
import { onMounted, ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const handleClick = (row) => {
    form.itemNumber = row.itemNumber
    form.itemName = row.itemName
    form.itemspecification = row.itemspecification
    form.itemType = row.itemType
    form.lotNumber = row.lotNumber
    form.manufactureDate = row.manufactureDate
    form.expirationDate = row.expirationDate
    form.plannedQuantity = row.plannedQuantity
    form.actualQuantity = row.actualQuantity
    form.unit = row.unit
    // 这里将生产订单号赋值给 selectedPackaging 来实现反填
    selectedPackaging.value = row.productionOrderNumber
    dialogFormVisible.value = true
}

const dialogFormVisible = ref(false)

const form = reactive({
    itemNumber: 0,
    itemName: "",
    itemspecification: "",
    itemType: "",
    lotNumber: "",
    manufactureDate: "",
    expirationDate: "",
    plannedQuantity: 0,
    actualQuantity: 0,
    unit: "",
    productionOrderNumber: ""
})

onMounted(() => {
    getMaterialPreparation();
    getpackaging();
})

const tableData = ref([{
    itemNumber: 0,
    itemName: "",
    itemspecification: "",
    itemType: "",
    lotNumber: "",
    manufactureDate: "",
    expirationDate: "",
    plannedQuantity: 0,
    actualQuantity: 0,
    unit: "",
    productionOrderNumber: ""
}])

const page = ref({
    pageindex: 1,
    pageSize: 10,
    totalCount: 0,
    totalPage: 0
})

const getpackaginglist = ref([{
    packagingPlanId: 0,
    productRange: "",
}])

const selectedPackaging = ref('')

//显示生产计划
const getpackaging = () => {
    axios.get('http://localhost:5118/api/PackagingPlan/GetPackagingPlan', {
        params: {
            PageIndex: 1,
            PageSize: 1000
        }
    }).then(res => {
        getpackaginglist.value = res.data.data.list
        console.log(getpackaginglist.value)
    })
}

// 处理生产订单号下拉框选择事件
const handlePackagingChange = (value) => {
    form.productionOrderNumber = value
}

const getMaterialPreparation = async () => {
    try {
        const response = await axios.get('http://localhost:5118/api/MaterialPreparation/Handle', {
            params: {
                TotalIndex: page.value.pageindex,
                TotalPage: page.value.pageSize
            }
        })
        console.log("物料", response)
        tableData.value = response.data.data
    } catch (error) {
        console.error(error)
    }
}

const handleDelete = async (row) => {
    try {
        const confirmResult = await ElMessageBox.confirm(
            '确认要删除这条记录吗？',
            '温馨提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        );
        if (confirmResult === 'confirm') {
            // 假设删除接口，需要根据实际情况修改
            await axios.post(`http://localhost:5293/api/MaterialPreparation/DelMaterialPreparation`, {
                itemNumber: row.itemNumber
            });
            ElMessage.success('删除成功');
            // 从表格数据中移除该条记录
            tableData.value = tableData.value.filter(item => item.itemNumber !== row.itemNumber);
        }
    } catch (error) {
        if (error instanceof Error && error.name === 'CancelError') {
            ElMessage.info('已取消删除操作');
        } else {
            ElMessage.error('删除失败，请稍后重试');
            console.error(error);
        }
    }
}

const submitForm = async () => {
    try {
        // 假设提交接口，根据实际情况修改
        await axios.post('http://localhost:5293/api/MaterialPreparation/UpdateMaterialPreparation', form).then(res => {
            if (res.data.code == 200) {
                ElMessage.success('提交成功');
                dialogFormVisible.value = false;
                getMaterialPreparation();
            } else {
                ElMessage.error('提交失败，请稍后重试');
            }
        }
        );

    } catch (error) {
        ElMessage.error('提交失败，请稍后重试');
        console.error(error);
    }
}

const resetForm = () => {
    form.itemName = "";
    form.itemspecification = "";
    form.itemType = "";
    form.lotNumber = "";
    form.manufactureDate = "";
    form.expirationDate = "";
    form.plannedQuantity = 0;
    form.actualQuantity = 0;
    form.unit = "";
    form.productionOrderNumber = "";
}
</script>